package com.web.exiaodao.business.controller;

import com.alibaba.fastjson.JSON;
import com.web.exiaodao.business.service.FranchiseTableService;
import com.web.exiaodao.remote.vo.FranchiseTableVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.controller.BaseController;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.util.jpa.WebUitl;
import com.web.webstart.base.util.result.XaResult;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * @author eason.zt
 * @version V1.0
 * @Title: FranchiseTableController.java
 * @Package com.web.webstart.business.controller
 * @Description: 加盟申请控制器
 * @date 2015年3月23日 下午1:00:00
 */
@Controller
@RequestMapping("/cms/franchiseTable")
public class FranchiseTableController extends BaseController {

    private static final Logger LOGGER = Logger.getLogger(FranchiseTableController.class);

    @Autowired
    private FranchiseTableService franchiseTableService;

    /**
     * @param pageSize
     * @param status     //默认查询非删除3的数据,具体类型参照XaConstant.Status
     * @param sortData
     * @param jsonFilter
     * @return
     * @Title: findFranchiseTableNEStatusPage
     * @Description: 分页查询FranchiseTable     * @param nextPage
     */
    @ResponseBody
    @RequestMapping(value = "findFranchiseTableNEStatusPage", method = RequestMethod.POST)
    public XaResult<Page<FranchiseTableVo>> findFranchiseTableNEStatusPage(
            @RequestParam(defaultValue = "0") Integer nextPage,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(defaultValue = "3") Integer status,
            @RequestParam(defaultValue = "[{property:'createTime',direction:'DESC'}]") String sortData,
            //过滤字段,字段名:jsonFilter,选填,默认:{},示例:{'search_EQ_field1':'value1','search_EQ_field2':'value2'},字段名称拼接规则search_为固定查询标识,EQ为等于,filed为字段名
            //EQ等于, IN包含, ISNULL空, LIKE, GT大于, LT小于, GTE大于等于, LTE小于等于, NE不等于,LIKEIGNORE非like
            @RequestParam(defaultValue = "{}") String jsonFilter
    ) throws BusinessException {
        XaResult<Page<FranchiseTableVo>> xr = new XaResult<>();
        try {
            Pageable pageable = WebUitl.buildPageRequest(nextPage, pageSize, sortData);
            Map<String, Object> filterParams = WebUitl.getParametersStartingWith(jsonFilter, "search_");
            return franchiseTableService.findListNEStatusByFilter(status, filterParams, pageable);
        } catch (Exception e) {
            LOGGER.error(XaConstant.Message.error, new Throwable(e));
            xr.error(XaConstant.Message.error);
        }
        return xr;
    }

    /**
     * @param pageSize
     * @param status     //默认查询正常状态1的数据,具体类型参照XaConstant.Status
     * @param sortData
     * @param jsonFilter
     * @return
     * @Title: findFranchiseTableEQStatusPage
     * @Description: (预留)分页查询FranchiseTable     * @param nextPage
     */
    @ResponseBody
    @RequestMapping(value = "findFranchiseTableEQStatusPage", method = RequestMethod.POST)
    public XaResult<Page<FranchiseTableVo>> findFranchiseTableEQStatusPage(
            @RequestParam(defaultValue = "0") Integer nextPage,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(defaultValue = "1") Integer status,
            @RequestParam(defaultValue = "[{property:'createTime',direction:'DESC'}]") String sortData,
            @RequestParam(defaultValue = "{}") String jsonFilter
    ) throws BusinessException {
        XaResult<Page<FranchiseTableVo>> xr = new XaResult<Page<FranchiseTableVo>>();
        try {
            Pageable pageable = WebUitl.buildPageRequest(nextPage, pageSize, sortData);
            Map<String, Object> filterParams = WebUitl.getParametersStartingWith(jsonFilter, "search_");
            return franchiseTableService.findListEQStatusByFilter(status, filterParams, pageable);
        } catch (Exception e) {
            LOGGER.error(XaConstant.Message.error, new Throwable(e));
            xr.error(XaConstant.Message.error);
        }
        return xr;
    }

    /**
     * @param modelId
     * @return
     * @Title: findFranchiseTableById
     * @Description: 根据ID查找单条实体
     */
    @ResponseBody
    @RequestMapping(value = "findFranchiseTableById", method = RequestMethod.POST)
    public XaResult<FranchiseTableVo> findFranchiseTableById(
            @RequestParam Long modelId
    ) throws BusinessException {
        XaResult<FranchiseTableVo> xr = new XaResult<FranchiseTableVo>();
        try {
            return franchiseTableService.findOne(modelId);
        } catch (Exception e) {
            LOGGER.error(XaConstant.Message.error, new Throwable(e));
            xr.error(XaConstant.Message.error);
        }
        return xr;
    }

    /**
     * @param model
     * @return
     * @Title: saveModel
     * @Description: 保存实体数据
     */
    @ResponseBody
    @RequestMapping(value = "saveFranchiseTable", method = RequestMethod.POST)
    public XaResult<FranchiseTableVo> saveFranchiseTable(
            FranchiseTableVo model
    ) throws BusinessException {
        XaResult<FranchiseTableVo> xr = new XaResult<FranchiseTableVo>();
        try {
            return franchiseTableService.saveOrUpdate(model);
        } catch (Exception e) {
            LOGGER.error(XaConstant.Message.error, new Throwable(e));
            xr.error(XaConstant.Message.error);
        }
        return xr;
    }

    /**
     * @param modelIds 多个实体id,中间用逗号隔开
     * @param status   操作类型,status类型见XaConstant.Status,默认删除操作
     * @return
     * @Title: multiOperateFranchiseTableByIds
     * @Description: 批量操作多个实体状态, 根据status进行操作
     */
    @ResponseBody
    @RequestMapping(value = "operateFranchiseTableByIds", method = RequestMethod.POST)
    public XaResult<FranchiseTableVo> operateFranchiseTableByIds(
            HttpServletRequest request,
            @RequestParam String modelIds,
            @RequestParam(defaultValue = "3") Integer status
    ) throws BusinessException {
        XaResult<FranchiseTableVo> xr = new XaResult<FranchiseTableVo>();
        try {
            return franchiseTableService.multiOperate(modelIds, status);
        } catch (Exception e) {
            LOGGER.error(XaConstant.Message.error, new Throwable(e));
            xr.error(XaConstant.Message.error);
        }
        return xr;
    }

    /**
     * 修改审核状态1:待审核(默认) 2：审核通过 3：审核拒绝 4：再审核
     *
     * @param request
     * @param modelIds
     * @return
     * @throws BusinessException
     */
    @ResponseBody
    @RequestMapping(value = "operateFranchiseStateTableByIds", method = RequestMethod.POST)
    public XaResult<FranchiseTableVo> operateFranchiseStateTableByIds(
            HttpServletRequest request,
            @RequestParam String modelIds,
            @RequestParam Integer franchise_State,
            @RequestParam String refuse_Reason
    ) throws BusinessException {
        XaResult<FranchiseTableVo> xr = new XaResult<FranchiseTableVo>();
        try {
            return franchiseTableService.multiOperatefranchiseState(modelIds, franchise_State, refuse_Reason);
        } catch (Exception e) {
            LOGGER.error(XaConstant.Message.error, new Throwable(e));
            xr.error(XaConstant.Message.error);
        }
        return xr;
    }

    /**
     * @param photoFile
     * @param request
     * @return
     * @Title: upload
     * @Description: 图片上传
     */
    @RequestMapping(value = "photoUpload", method = RequestMethod.POST)
    public void photoUpload(
            @RequestParam(value = "photoFile", required = false) MultipartFile photoFile,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws BusinessException {
        String result = "";
        String root = request.getSession().getServletContext().getRealPath("/");
        String picturePath = "/upload/franchiseTable";
        String ext = photoFile.getOriginalFilename().substring(photoFile.getOriginalFilename().lastIndexOf("."));
        String newName = new Date().getTime() + ext;
        File filedict = new File(root + picturePath);
        if (!filedict.exists()) {
            filedict.mkdir();
        }
        File targetFile = new File(root + picturePath + File.separator + newName);
        try {
            if (StringUtils.equalsIgnoreCase(ext, ".jpg") || StringUtils.equalsIgnoreCase(ext, ".png")) {
                photoFile.transferTo(targetFile);
                BufferedImage bimg = ImageIO.read(targetFile);
                int width = bimg.getWidth();
                int height = bimg.getHeight();
                result = picturePath + "/" + newName + "," + width + "," + height;
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().print(JSON.toJSONString(result));
            } else {
                LOGGER.info("上传文件类型不允许,请上传jpg/png图片");
                throw new BusinessException("上传文件类型不允许,请上传jpg/png图片");
            }
        } catch (IllegalStateException e) {
            throw new BusinessException("图片上传失败");
        } catch (IOException e) {
            throw new BusinessException("图片上传失败");
        } catch (Exception e) {
            throw new BusinessException("图片上传失败");
        }
    }

}

